package cn.tedu.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet Filter implementation class CheckLoginFilter
 */
public class CheckLoginFilter implements Filter {
	private String redirectURL;
	private String sessionKey=null;
	private List<String> notCheckURLList=new ArrayList<String>();
    /**
     * Default constructor. 
     */
    public CheckLoginFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
		//1.强制转换成成http
		HttpServletRequest request=(HttpServletRequest)servletRequest;
		HttpServletResponse response=(HttpServletResponse)servletResponse;
		//2.获取当前浏览器对应的session对象
		HttpSession session=request.getSession();
		//3.如果sessionkey=null,表示直接访问下一个过滤器
		//直接请求了目标资源,即相当于空走过滤器
		if(this.sessionKey==null || "".equals(this.sessionKey)) {
			filterChain.doFilter(servletRequest, servletResponse);
			return;//终止当前方法
		}
		//4.必须要检查是否登录过
		//!checkRequestURLNotFilterList(request),不在免检列表
		//session.getAttribute(this.sessionKey)==null则一定没有登录过
		if(!checkRequestURLNotFilterList(request)  &&
			session.getAttribute(this.sessionKey)==null) {
			//http://localhost:8080/tmwp/login.jsp
			response.sendRedirect(request.getContextPath()+this.redirectURL);
			return;
		}
		//5.上面的两个if条件都没有成立,则需要访问下一个过滤器
		//可能是登录过,也可能是免检过的,或者是即是登录过的也是免检过的
		filterChain.doFilter(servletRequest, servletResponse);
	}
    private boolean checkRequestURLNotFilterList(HttpServletRequest request) {
    	String uri=request.getServletPath()+(request.getPathInfo()==null? "" : request.getPathInfo());
    	System.out.println(uri);
    	return this.notCheckURLList.contains(uri);
    }
	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		this.redirectURL=fConfig.getInitParameter("redirectURL");
		this.sessionKey=fConfig.getInitParameter("checkSessionKey");
		String notCheckURLList=fConfig.getInitParameter("notCheckURL");
		if(notCheckURLList!=null) {
			this.notCheckURLList.clear();
			//有不需要检测的url列表      token:令牌
			StringTokenizer st=new  StringTokenizer(notCheckURLList,";");
			while(st.hasMoreTokens()) {
				this.notCheckURLList.add(st.nextToken());
			}
		}
	}

}
